Lua Quick Start Guide: The easiest way to learn Lua programming by Gabor Szauer

Lua Quick Start Guide: The easiest way to learn Lua programming by Gabor Szauer

Author:Gabor Szauer [Szauer, Gabor]
Language: eng
Format: epub
Tags: COM051010 - COMPUTERS / Programming Languages / General, COM060160 - COMPUTERS / Web / Web Programming, COM051260 - COMPUTERS / Programming Languages / JavaScript
Publisher: Packt Publishing
Published: 2018-07-26T23:00:00+00:00


Animal.new = function(self, object)

object = object or {}

setmetatable(object, self)

self.__index = self

return object

end

Animal.MakeSound = function(self)

print(self.sound)

end

Not every animal is going to make the same sound. Create two new classes, dog and cat, that extend Animal:

-- Dog is a class, not an object (instance)

Dog = Animal:new()

Dog.sound = "woof"

-- Cat is a class, not an Object (instance)

Cat = Animal:new()

Cat.sound = "meow"

Cat.angry = false

Cat.MakeSound = function(self)

if self.angry then

print("hissss)

else

print(self.sound)

end

end

In this code, Dog is a new class, not an instance of the Animal class. This can be a bit tricky at first, as the syntax is similar. Dog simply overrides the sound variable. Cat also extends Animal. But Cat provides its own implementation of MakeSound, which lets the cat make different sounds.

Regardless of whether an animal is a Cat or a Dog, we can treat them both as an Animal. We know that every object that is a Cat or a Dog is also an Animal. And we know that every Animal has a MakeSound function. The following code generates some animals and has them all make sounds:

animals = { Cat:new(), Dog:new(), Cat:new() }

animals[1].angry = true



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.